package com.ruiysoft.pub;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCacheMybatis implements Cache {
    private static final Logger log = LoggerFactory.getLogger(RedisCacheMybatis.class);
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private RedisTemplate redisTemplate;
    private String id;
    public RedisCacheMybatis(String id){

        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        log.info("redisCache-{}",id);
        this.id = id;
    }

    @Override
    public String getId() {
        log.info("redisCache-{}",id);
        log.info("redisCache-getId");
        return this.id;
    }

    @Override
    public void putObject(Object o, Object o1) {
        redisTemplate = getRedisTemplate();
        log.info("redisCache-{}",id);
        log.info("redisCache-putObject-{}-{}",JSONObject.toJSONString(o),JSONObject.toJSONString(o1));
        redisTemplate.opsForHash().put(id,o,o1);
    }

    @Override
    public Object getObject(Object o) {
        redisTemplate = getRedisTemplate();
        log.info("redisCache-{}",id);
        log.info("redisCache-getObject-{}",JSONObject.toJSONString(o));
        return redisTemplate.opsForHash().get(id,o);
    }

    @Override
    public Object removeObject(Object o) {
        redisTemplate = getRedisTemplate();
        log.info("redisCache-{}",id);
        log.info("redisCache-removeObject-{}",JSONObject.toJSONString(o));
        return redisTemplate.opsForHash().delete(id,o);
    }

    @Override
    public void clear() {
        redisTemplate = getRedisTemplate();
        log.info("redisCache-{}",id);
        log.info("redisCache-clear");
        redisTemplate.delete(id);
    }

    @Override
    public int getSize() {
        redisTemplate = getRedisTemplate();
        log.info("redisCache-{}",id);
        log.info("redisCache-getSize");
        return redisTemplate.opsForHash().size(id).intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        log.info("redisCache-{}",id);
        log.info("redisCache-getReadWriteLock");
        return this.readWriteLock;
    }

    private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }

}
